import { axios } from '@/utils/request'
import { notification } from 'ant-design-vue'

const downloadUrl = '/system/common/download'

export const mimeMap = {
  xls: 'application/vnd.ms-excel',
  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  zip: 'application/zip',
  xml: 'application/xml'
}

/**
 * 下载.xlsx文件
 * @param {String} filename 文件名
 */
export function downloadXlsx(filename) {
  axios({
    url: downloadUrl,
    method: 'get',
    params: { fileName: filename, delete: true },
    responseType: 'blob',
    timeout: 0
  }).then(res => {
    resolveBlob(res, mimeMap.xlsx)
  })
}

/**
 * 代码生成并下载为zip
 * @param {String} url 链接
 * @param {String} tables 表名
 */
export function genCodeZip(url, tables) {
  axios({
    url: url,
    method: 'get',
    params: { tables: tables },
    responseType: 'blob',
    timeout: 0
  }).then(res => {
    resolveBlob(res, mimeMap.zip)
  })
}

/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export function resolveBlob(res, mimeType) {
  if(is_weixin()){
    notification.warning({
      message: '提示:',
      description: h => {
        return [
          h('div','微信浏览器暂不支持下载,如需进行更多操作'),
          h('div', { class: 'colorZS' },'请点击右上角进入默认浏览器操作')
        ]
      },
    });
    return
  }
  const aLink = document.createElement('a')
  var blob = new Blob([res.data], { type: mimeType })
  // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  var contentDisposition = decodeURI(res.headers['content-disposition'])
  var result = patt.exec(contentDisposition)
  var fileName = result[1]
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', fileName) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  document.body.removeChild(aLink)
  window.URL.revokeObjectURL(aLink.href)
}

/**
 * 直接下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export function resolveUrl(res, mimeType, name) {
  if(is_weixin()){
    notification.warning({
      message: '提示:',
      description: h => {
        return [
          h('div','微信浏览器暂不支持下载,如需进行更多操作'),
          h('div', { class: 'colorZS' },'请点击右上角进入默认浏览器操作')
        ]
      },
    });
    return
  }
  
  const aLink = document.createElement('a')
  //  no-undef-init
  var blob = undefined
  if (mimeType) {
    blob = new Blob([res.data], { type: mimeType })
  } else {
    blob = new Blob([res.data])
  }
  // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  var fileName = name
  fileName = fileName.replace(/"/ig, '')
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', fileName) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  document.body.removeChild(aLink)
  window.URL.revokeObjectURL(aLink.href)
}

/**
 * 机械blob文件返回JSON
 * **/

export function readAsText(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsText(file, 'utf-8')
    reader.onload = function () {
      try {
        if (typeof JSON.parse(reader.result) == "object") {
          resolve(JSON.parse(reader.result))
        }
      } catch(e) {
        resolve(reader.result)
      }
    }
  })
}
// 判断是否是微信浏览器, 微信浏览器不支持下载
function is_weixin() {
    var ua = window.navigator.userAgent.toLowerCase(); 
    if (ua.match(/MicroMessenger/i) == 'micromessenger') { 
        return true;
    } else { 
        return false;
    } 
}
